<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select v-model="formData.deptId" :data="deptList" :props="defaultProps" check-strictly
              node-key="id" placeholder="请选择归属部门" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" maxlength="11" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formData.email" maxlength="50" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="formData.id === undefined">
        <el-col :span="12">
          <el-form-item label="用户账号" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户账号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-select v-model="formData.sex" placeholder="请选择用户性别">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-else>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-select v-model="formData.sex" placeholder="请选择用户性别">
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="false" :span="12">
          <el-form-item label="岗位">
            <el-select v-model="formData.postIds" multiple placeholder="请选择">
              <el-option v-for="item in postList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" v-if="false">
          <el-form-item label="岗位">
            <el-select v-model="formData.postIds" multiple placeholder="请选择">
              <el-option v-for="item in postList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" style="display: none">
          <el-form-item label="外部用户" prop="userAccountType">
            <el-select v-model="formData.userAccountType" placeholder="请选择" @change="selectUserAccount">
              <!-- <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.USER_ACCOUNT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              /> -->
              <el-option :value="0" :key="0" label="否"></el-option>
              <el-option :value="1" :key="1" label="是"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12" v-if="showFlag">
          <el-form-item label="承运商" prop="enterpriseId">
            <el-select v-model="formData.enterpriseId" placeholder="请选择">
              <el-option v-for="dict in carrierLists" :key="dict.id" :label="dict.customerName" :value="dict.id"
                @click="handleshippersName(dict)" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formData.remark" placeholder="请输入内容" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" name="SystemUserForm" setup>
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import { CommonStatusEnum } from '@/utils/constants'
  import * as CustMgrApi from '@/api/queue/custMgr'
  import { defaultProps, handleTree } from '@/utils/tree'
  import * as PostApi from '@/api/system/post'
  import * as DeptApi from '@/api/system/dept'
  import * as UserApi from '@/api/system/user'

  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗

  const dialogVisible = ref(false) // 弹窗的是否展示
  const dialogTitle = ref('') // 弹窗的标题
  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const formType = ref('') // 表单的类型：create - 新增；update - 修改
  const carrierLists = ref([])
  const formData = ref({
    nickname: '',
    deptId: '',
    mobile: '',
    email: '',
    id: undefined,
    username: '',
    sex: undefined,
    postIds: [],
    remark: '',
    userAccountType: 0,
    enterpriseId: undefined,
    enterpriseName: undefined,
    status: CommonStatusEnum.ENABLE,
    roleIds: []
  })
  const formRules = reactive({
    username: [{ required: true, message: '用户账号不能为空', trigger: 'blur' }],
    userAccountType: [{ required: false, message: '外部用户不能为空', trigger: 'blur' }],
    nickname: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
    enterpriseId: [{ required: true, message: '承运商不能为空', trigger: 'blur' }],
    email: [
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: ['blur', 'change']
      }
    ],
    mobile: [
      {
        required: true,
        message: '手机号码不能为空',
        trigger: 'blur'
      },
      {
        pattern: /^1\d{10}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ]
  })
  const formRef = ref() // 表单 Ref
  const deptList = ref < Tree[] > ([]) // 树形结构
  const postList = ref([]) // 岗位列表
  const getcarrierLists = async (id) => {
    try {
      carrierLists.value = await CustMgrApi.getcarrierLists(id)
    } finally {
    }
  }

  let showFlag = ref(false)
  const selectUserAccount = (e) => {
    showFlag.value = e == 1 ? true : false
  }
  //处理承运商

  let handleshippersName = (val) => {
    LOG.Log(val)
    formData.value.enterpriseName = val.customerName
  }
  /** 打开弹窗 */
  const open = async (type: string, id?: number) => {
    dialogVisible.value = true
    showFlag.value = false
    dialogTitle.value = t('action.' + type)
    formType.value = type
    resetForm()
    // 修改时，设置数据
    if (id) {
      formLoading.value = true
      try {
        formData.value = await UserApi.getUser(id)
        if (formData.value.userAccountType == 1) showFlag.value = true
        if (!formData.value.sex) formData.value.sex = undefined
      } finally {
        formLoading.value = false
      }
    }
    // 加载部门树
    deptList.value = handleTree(await DeptApi.getSimpleDeptList())
    // 加载岗位列表
    postList.value = await PostApi.getSimplePostList()
    // getcarrierLists(1)
  }
  defineExpose({ open }) // 提供 open 方法，用于打开弹窗

  /** 提交表单 */
  const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
  const submitForm = async () => {
    // 校验表单
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    // 提交请求
    formLoading.value = true
    try {
      const data = formData.value as unknown as UserApi.UserVO
      if (formType.value === 'create') {
        await UserApi.createUser(data)
        message.success(t('common.createSuccess'))
      } else {
        await UserApi.updateUser(data)
        message.success(t('common.updateSuccess'))
      }
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  }

  /** 重置表单 */
  const resetForm = () => {
    formData.value = {
      nickname: '',
      deptId: '',
      mobile: '',
      email: '',
      id: undefined,
      enterpriseId: undefined,
      enterpriseName: undefined,
      username: '',
      sex: undefined,
      postIds: [],
      remark: '',
      userAccountType: 0,
      status: CommonStatusEnum.ENABLE,
      roleIds: []
    }
    formRef.value?.resetFields()
  }
</script>